﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using Sispe.Entities;
using Sispe.BussinesLogic;
using Microsoft.Practices.Unity;

namespace Sispe.UI
{
    public partial class FrmAttendaceManagement : Form
    {
        [Dependency]
        public IPersonaBL personaBL { get; set; }

        [Dependency]
        public IContratoBL contratoBL { get; set; }

        [Dependency]
        public ITareoBL tareoBL { get; set; }

        public FrmAttendaceManagement()
        {
            InitializeComponent();
            this.BuildUp();
        }

        //Create Standalone SDK class dynamicly.
        //public zkemkeeper.CZKEMClass axCZKEM1 = new zkemkeeper.CZKEMClass();
        public zkemkeeper.CZKEM axCZKEM1 = new zkemkeeper.CZKEM();
        List<TAREO_BORRADOR> tareoBorrador = null;

        /********************************************************************************************************************************************
        * Before you refer to this demo,we strongly suggest you read the development manual deeply first.                                           *
        * This part is for demonstrating the communication with your device.There are 3 communication ways: "TCP/IP","Serial Port" and "USB Client".*
        * The communication way which you can use duing to the model of the device.                                                                 *
        * *******************************************************************************************************************************************/
        //#region Communication
        private bool bIsConnected = false;//the boolean value identifies whether the device is connected
        private int iMachineNumber = 1;//the serial number of the device.After connecting the device ,this value will be changed.

        //If your device supports the TCP/IP communications, you can refer to this.
        //when you are using the tcp/ip communication,you can distinguish different devices by their IP address.

        private void btnConnect_Click(object sender, EventArgs e)
        {
            if (txtIP.Text.Trim() == "" || txtPort.Text.Trim() == "")
            {
                MessageBox.Show("La Dirección IP o el Puerto no pueden estar vacíos.", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            int idwErrorCode = 0;

            Cursor = Cursors.WaitCursor;
            if (btnConnect.Text == "Desconectar")
            {
                axCZKEM1.Disconnect();
                bIsConnected = false;
                btnConnect.Text = "Conectar";
                lblState.Text = "Estado del Dispositivo: Desconectado.";
                lblState.ForeColor = Color.Crimson;
                Cursor = Cursors.Default;
                return;
            }

            bIsConnected = axCZKEM1.Connect_Net(txtIP.Text, Convert.ToInt32(txtPort.Text));
            if (bIsConnected == true)
            {
                btnConnect.Text = "Desconectar";
                btnConnect.Refresh();
                lblState.Text = "Estado del Dispositivo: Conectado";
                lblState.ForeColor = Color.Green;
                iMachineNumber = 1;//In fact,when you are using the tcp/ip communication,this parameter will be ignored,that is any integer will all right.Here we use 1.
                axCZKEM1.RegEvent(iMachineNumber, 65535);//Here you can register the realtime events that you want to be triggered(the parameters 65535 means registering all)
            }
            else
            {
                axCZKEM1.GetLastError(ref idwErrorCode);
                MessageBox.Show("No se puede conectar con el Dispositivo, ErrorCode=" + idwErrorCode.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            Cursor = Cursors.Default;
        }

        private void btnDescargarRegistro_Click(object sender, EventArgs e)
        {
            if (bIsConnected == false)
            {
                MessageBox.Show("Conecte primero el dispositivo por favor.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            string sdwEnrollNumber = "";
            int idwTMachineNumber = 0;
            int idwEMachineNumber = 0;
            int idwVerifyMode = 0;
            int idwInOutMode = 0;
            int idwYear = 0;
            int idwMonth = 0;
            int idwDay = 0;
            int idwHour = 0;
            int idwMinute = 0;
            int idwSecond = 0;
            int idwWorkcode = 0;

            int idwErrorCode = 0;
            int iGLCount = 0;
            int iIndex = 0;
            int iValue = 0;
            tareoBorrador = new List<TAREO_BORRADOR>();
            var msg = "ERROR";

            Cursor = Cursors.WaitCursor;
            //lvLogs.Items.Clear();
            axCZKEM1.EnableDevice(iMachineNumber, false);//disable the device
            if (axCZKEM1.ReadGeneralLogData(iMachineNumber))//read all the attendance records to the memory
            {
                while (axCZKEM1.SSR_GetGeneralLogData(iMachineNumber, out sdwEnrollNumber, out idwVerifyMode,
                           out idwInOutMode, out idwYear, out idwMonth, out idwDay, out idwHour, out idwMinute, out idwSecond, ref idwWorkcode))//get records from the memory
                {
                    iGLCount++;
                    var tareo = new TAREO_BORRADOR()
                    {
                        EnrollNumber = sdwEnrollNumber,
                        VerifyMode = idwVerifyMode,
                        InOutMode = idwInOutMode,
                        Date = Convert.ToDateTime(idwYear.ToString() + "/" + idwMonth.ToString() + "/" + idwDay.ToString() + " " + 
                                                  idwHour.ToString() + ":" + idwMinute.ToString() + ":" + idwSecond.ToString()),
                        WorkCode = idwWorkcode,
                        Reserved = 0,
                        Existe = false,
                        Contrato = false,
                        Estado = false,
                        Tareo = false
                    };
                    tareoBorrador.Add(tareo);
                    iIndex++;
                }
                
                try
                {
                    //Una vez guardada la lista de Tareos pasamos a revisar los datos
                    foreach (var item in tareoBorrador)
                    {
                        //item.EnrollNumber = Evaluar DNI para ver si existe la persona en la BD
                        var persona = personaBL.GetFromPersonaByDni(item.EnrollNumber);

                        if (persona != null)
                        {
                            item.Existe = true;

                            //Ahora vemos si la persona en si tiene un contrato vigente.
                            //var contrato = contratoBL.GetFromContratoVigenteByTrabajador(persona.IdPersona);
                            var contrato = contratoBL.GetFromContratosPorVencerByIdTrabajador(persona.IdPersona);

                            if (contrato != null)
                            {
                                item.Contrato = true;
                                item.Estado = true;
                            }
                        }

                        tareoBL.AddTareoBorrador(item);
                    }
                    //Limpiamos Registro del dispositivo
                    axCZKEM1.EnableDevice(iMachineNumber, false);//disable the device
                    if (axCZKEM1.ClearGLog(iMachineNumber))
                    {
                        axCZKEM1.RefreshData(iMachineNumber);//the data in the device should be refreshed
                        if (axCZKEM1.GetDeviceStatus(iMachineNumber, 6, ref iValue)) //Here we use the function "GetDeviceStatus" to get the record's count.The parameter "Status" is 6.
                        {
                            MessageBox.Show("Registro Correcto.", "Correcto!", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                    }
                    else
                    {
                        axCZKEM1.GetLastError(ref idwErrorCode);
                    }
                    axCZKEM1.EnableDevice(iMachineNumber, true);//enable the device                    
                }
                catch (Exception ex)
                {
                    msg = ex.Message;
                    MessageBox.Show(msg, "Error!", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                
            }
            else
            {
                Cursor = Cursors.Default;
                axCZKEM1.GetLastError(ref idwErrorCode);

                if (idwErrorCode != 0)
                {
                    MessageBox.Show("Error al tratar de leer los datos del Dispositivo, ErrorCode: " + idwErrorCode.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    MessageBox.Show("No existe registro alguno a descargar del dispositivo.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            axCZKEM1.EnableDevice(iMachineNumber, true);//enable the device
            Cursor = Cursors.Default;
        }
    }
}
